#include <dblib.h>
#include <DM_Soundex.h>
#include <params.h>
#include <stdafx.h>
#include <stdexcept>

#ifdef __cplusplus
extern "C" {
#endif

RETCODE __declspec(dllexport) xp_phon_dm(SRV_PROC *srvproc);

#ifdef __cplusplus
}
#endif

RETCODE __declspec(dllexport) xp_phon_dm(SRV_PROC *srvproc)
{
	RETCODE rc = XP_NOERROR;
	int RowCount = 0;
	int k = 0;
	DM_Soundex s;
	params *p1 = new params();
	int numparams = params::getparamcount(srvproc);
	try {
		if (numparams != 1) {
			Dblib::printerror(srvproc, USAGE_DM);
			rc = XP_ERROR;
		}
		if (rc == XP_NOERROR) {
			params::getparam(srvproc, 1, p1);
			int i = (int)p1->length;
			k = s.Encode(p1->cdata, i);
		}
	} catch (std::exception ex) {
		Dblib::printerror(srvproc, ERR_DM_EXCEPTION);
		rc = XP_ERROR;
	}
	
	srv_describe(srvproc, 1, "Num", SRV_NULLTERM, SRVINT4, 0, SRVINT4, 0, 0);
	srv_describe(srvproc, 2, "Code", SRV_NULLTERM, SRVINT4, 0, SRVINT4, 0, 0);
	
	if (rc != XP_ERROR) {
		for (int n = 0; n < k; n++) {
			// Grab the first character
			BYTE p = *(s.DM_Encodings + n * 8);
			// If the first character is not '\0', we send it back to the client
			if (p != '\0') {
				// Increment the row count
				RowCount++;
				int j = atoi((char *)s.DM_Encodings + n *8);
				// Send the row back to the client
                //_snprintf(SqlText, 6, (const char *)s.DM_Encodings + n * 8);
				srv_setcoldata(srvproc, 1, &RowCount);
				srv_setcoldata(srvproc, 2, &j);
				srv_setcollen(srvproc, 2, 6);
				// Send the entire row
				srv_sendrow(srvproc);
			}
		}
	}
	// Send a done message with the row count
	srv_senddone(srvproc, SRV_DONE_COUNT, (DBUSMALLINT)0, (DBINT)RowCount);
	// Now return the number of rows processed
	return rc;
}

